<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Model\Device;
use App\Model\DeviceThree;
use App\Model\DeviceTwo;
use App\Model\Group;
use App\Model\InverterData;
use App\Model\InverterDataThree;
use App\Model\InverterDataTwo;
use App\Model\Site;
use App\Model\StatisticsDayEnergy;
use Illuminate\Http\Request;
use Redis;

class IndexController extends Controller
{
    public function base()
    {
        $user = $this->_getCurrentUser();
        return view('frontend.base', ['user' => $user]);
    }

    public function getIndex()
    {
        $user = $this->_getCurrentUser();
        $sites = Site::getSitesByUserId($user->id);
        $user_id = $user->id;
//        if($user->id < 17){
//            $devices_count = Device::getDevicesCountByUserId($user->id);
//        }else{
//            $devices_count = DeviceTwo::getDevicesCountByUserId($user->id);
//        }
        switch ($user_id){
            case $user_id < 17:
                $devices_count = Device::getDevicesCountByUserId($user->id);
                break;
            case $user_id >=17 && $user_id < 43;
                $devices_count = DeviceTwo::getDevicesCountByUserId($user->id);
                break;
            default:
                $devices_count = DeviceThree::getDevicesCountByUserId($user->id);
        }
        $begin_date = date('Y-m-d', strtotime('-30 day'));
        $end_date = date('Y-m-d');

        return view('frontend.index.index', [
            'user'  =>$user,
            'sites' => $sites,
            'devices_count' => $devices_count,
            'begin_date' => $begin_date,
            'end_date' => $end_date
        ]);

    }

    public function getTotalData()
    {
        $user = $this->_getCurrentUser();
        $user_id =  $user->id;
//        if($user_id < 17) {
//            $data = InverterData::getLastInverterData($user_id);
//            $today_gen_cap = $data['today_gen_cap'] ;
//            $year_gen_cap = $data['total_gen_cap'] - InverterData::getYearGenCapByUserId($user->id) - $data['total_offset'];
//            $sunshine_peak_hours = $today_gen_cap / (Device::getAllActualPowerByUserId($user->id) / 1000);
//        }else{
//            $data = InverterDataTwo::getLastInverterData($user_id);
//            $today_gen_cap = $data['today_gen_cap'] ;
//            $year_gen_cap = $data['total_gen_cap'] - InverterDataTwo::getYearGenCapByUserId($user->id)  - $data['total_offset'];
//            $sunshine_peak_hours = $today_gen_cap / (DeviceTwo::getAllActualPowerByUserId($user->id) / 1000);
//        }

        switch ($user_id){
            case $user_id < 17:
                 $data = InverterData::getLastInverterData($user_id);
                 $today_gen_cap = $data['today_gen_cap'] ;
                 $year_gen_cap = $data['total_gen_cap'] - InverterData::getYearGenCapByUserId($user->id) - $data['total_offset'];
                 $sunshine_peak_hours = $today_gen_cap / (Device::getAllActualPowerByUserId($user->id) / 1000);
                break;
            case $user_id >=17 && $user_id < 43;
                if ($user_id != 20){
                    $data = InverterDataTwo::getLastInverterData($user_id);
                }else{
                    $data = $this->_LastInverterDataByRedis(21);
                }
                $today_gen_cap = $data['today_gen_cap'] ;
                $year_gen_cap = $data['total_gen_cap'] - InverterDataTwo::getYearGenCapByUserId($user->id)  - $data['total_offset'];
                $sunshine_peak_hours = $today_gen_cap / (DeviceTwo::getAllActualPowerByUserId($user->id) / 1000);
                break;
            default:
                $data = InverterDataThree::getLastInverterData($user_id);
                $today_gen_cap = $data['today_gen_cap'] ;
                $year_gen_cap = $data['total_gen_cap'] - InverterDataThree::getYearGenCapByUserId($user->id)  - $data['total_offset'];
                $sunshine_peak_hours = $today_gen_cap / (DeviceThree::getAllActualPowerByUserId($user->id) / 1000);
        }

        $today_gen_cap = $data['today_gen_cap'] ;
        $month_gen_cap = $data['month_gen_cap'] ;
        $total_gen_cap = $data['total_gen_cap'] ;
        $working_devices_count = $data['count'];
//        $today_gen_cap = InverterData::getTodayGenCapByUserId($user->id);
//        $month_gen_cap = InverterData::getMonthGenCapByUserId($user->id);
//        $total_gen_cap = InverterData::getTotalGenCapByUserId($user->id);

//        $year_gen_cap = $data['total_gen_cap'] - InverterData::getYearGenCapByUserId($user->id);
//        $year_gen_cap = $total_gen_cap;


        $sunshine_peak_hours = round($sunshine_peak_hours, 3);


        $result = [
            'working_devices_count' => $working_devices_count,
            'today_gen_cap' => $today_gen_cap/1000,
            'month_gen_cap' => $month_gen_cap/1000,
            'year_gen_cap' => $year_gen_cap/1000 + $user->year_offset,
//            'year_gen_cap' => $month_gen_cap/1000,
            'total_gen_cap' => $total_gen_cap/1000,
            'sunshine_peak_hours' => $sunshine_peak_hours,
        ];

        return $this->json_success($result);

    }

    public function getRealTime()
    {
        $user = $this->_getCurrentUser();
        return view('frontend.index.real-time');
    }

    public function getEnergyData(Request $request)
    {
        $type = $request->input('type');
        $time_type = $request->input('time_type');
        $start = $request->input('start');
        $end = $request->input('end');

        $user = $this->_getCurrentUser();

        $start_date = strtotime($start);
        $end_date = strtotime($end);

        $result = [];
        //电脑数据
        if ($type == 'energy') {
            $labels = ['0'];
            $datas = ['0'];
            if ($time_type == 'h') {
                return $this->json_error('不能按时段查询发电量！', 1001);
            }
            if ($time_type == 'm') {
                $s_y = (int)date('Y', $start_date);
                $s_m = (int)date('m', $start_date);
                $e_y = (int)date('Y', $end_date);
                $e_m = (int)date('m', $end_date);
                $interval_month = 12 * ($e_y - $s_y) + ($e_m - $s_m);


                for ($i = 0; $i <= $interval_month; $i++) {
                    $m = date('Y-m', strtotime('+' . $i . ' month', $start_date));
                    array_push($labels, $m);
                    $energy = StatisticsDayEnergy::getOneMonthByUserId($user->id, $m);
                    array_push($datas, $energy);
                }

            }
            if ($time_type == 'd') {
                $sdes = StatisticsDayEnergy::getSomeByUserId($user->id, $start, $end);
                $labels = ['0'];
                $datas = ['0'];
                foreach ($sdes as $sde) {

                    array_push($labels, $sde->date);
                    array_push($datas, $sde->site_value);
                }
            }
            $result['labels'] = $labels;
            $result['data'] = $datas;
            return $this->json_success($result);
        }
        //功率数据
        if ($type == 'power') {
            //TODO
        }

        return $this->json_error('不支持的类型！', 1002);


    }

    public  function  getProjectInfo()
    {
        $province="";
        $city="";
        $town="";
        $address="";
        $user=$this->_getCurrentUser();
        $user_id = $user->id;
        $groups_num = Group::getGroupsTotalByUserId($user->id);
//        if($user->id <17) {
//            $device_num = Device::getDevicesCountByUserId($user->id);
//        }else{
//            $device_num = DeviceTwo::getDevicesCountByUserId($user->id);
//        }
        switch ($user_id){
            case $user_id<17:
                $device_num = Device::getDevicesCountByUserId($user->id);
                break;
            case $user_id>=17&&$user_id<43:
                $device_num = DeviceTwo::getDevicesCountByUserId($user->id);
                break;
            default:
                $device_num = DeviceThree::getDevicesCountByUserId($user->id);
        }
        $sites=Site::getSitesByUserId($user->id);
        foreach($sites as $site)
        {
            $province=$site->province;
            $city=$site->city;
            $town=$site->town;
            $address=$site->address;
        }
        $result=[
            'groups'=>$groups_num,
            'devices'=>$device_num,
            'city'=>$city,
            'province'=>$province,
            'town'=>$town,
            'address'=>$address
        ];
        return $this->json_success($result);
    }




    private function _LastInverterDataByRedis($site_id){
        $today_gen_cap = 0;

        $month_gen_cap = 0;

        $total_gen_cap = 0;

        $total_offset = 0;
        $redis = $this->_Redis();
        $count = 0;
        $key = 'xy:industry:data:' . $site_id . ':*';
        $keys = $redis->keys($key);
        $pipe = $redis->multi(Redis::PIPELINE);
        foreach ($keys as $k) {
            $pipe->get($k);
        }
        $results = $pipe->exec();
        if($results) {
            foreach ($results as $result) {
                try {
                    if ($result) {
                        $arr = json_decode($result, true);
                        if (array_key_exists("created_at", $arr)) {
                            $st = strtotime($arr['created_at']);
                        } else {
                            $st = strtotime($arr['EventTime']);
                        }
                        if (date('Y-m-d', $st) == date('Y-m-d')) {
                            if (time() - $st < 3600) {
                                $created_at = strtotime($arr ['EventTime']);
                                $now = time();
                                if ($now - $created_at < 60 * 60) {
                                    //最近一次非警报状态则正常运行
                                    $count++;
                                }
//                dump($obj);
                                $today_gen_cap += $arr ['DayGenCap'];
                                $month_gen_cap += $arr['MonthGenCap'];
                                $total_gen_cap += $arr['TotGenCap'];
                            } else {
                                $month_gen_cap += $arr['MonthGenCap'];
                                $total_gen_cap += $arr['TotGenCap'];
                            }
                        }
                    }
                }catch (\Exception $e){
//                   dump($e->getMessage());
                }
            }
        }

        $re['today_gen_cap'] = $today_gen_cap;
        $re['month_gen_cap'] = $month_gen_cap;
        $re['total_gen_cap'] = $total_gen_cap;
        $re['total_offset'] = $total_offset;
        $re['count'] = $count;
        return $re;
    }
}
